import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
//StatefulWidget 有状态的组件是真正的状态组件本体，用于接受外部船坞的数据
 class StatefullCase extends StatefulWidget{
    // 出于性能优化考虑，组件都推荐添加 const 保持组件不可变性

 const StatefullCase({super.key, this.title='状态管理'});

   // 定义一个属性，用于接收外部传入的数据

 final String title;
  @override
  createState() => _StatefullCaseState();
}
//State 时组件的状态类，单独管理组件的状态. UI更新.生命周期
class _StatefullCaseState extends State<StatefullCase>{
  int count=0;
  List channelList=[
  ];
  @override
  void initState() {
    super.initState();
   //初始化状态
   count=10;
   //组件初始化时调用
   getChannelList();
  }
  void getChannelList()async{
    //1.创建Dio对象
    Dio dio=Dio();
    //2.发送请求
    final res=await dio.get('https://geek.itheima.net/v1_0/channels');
    
    //3.解析数据
    setState(() {
      channelList=res.data['data']['channels'];
    });
    print(res.data['data']['channels']);
  }
  @override
  void dispose() {
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
     // 打印组件的属性
    // print('组件的build函数被调用了');
    return Center(
      child: Center(
        child:Column(
          children: [
            Text('父传子${widget.title}'),
            ElevatedButton(
              onPressed: (){
                setState(() {
                  count++;
                });
              }, child:  Text('点击+1---$count'),),
              Text('数据长度${channelList.length}'),
              Expanded(
                flex: 1,
                child: ListView.builder(
                  itemCount: channelList.length,

                  itemBuilder: (context,index){
                    return Container(
                      height: 100,
                      margin: EdgeInsets.symmetric(horizontal: 10,vertical: 5),
                     width: double.infinity,
                     color: Colors.green,
                      child: Text(channelList[index]['name']),
                    );
                  },
                ),
              )
          ],
        ),
      ),
    );
  }
}
